package com.ly.wxstore.web.account;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ly.wxstore.service.account.ShiroDbRealm;
import com.ly.wxstore.service.account.WeixinOAuthAuthenticationFilter;
import com.ly.wxstore.service.account.WeixinOAuthToken;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * 
 * 真正登录的POST请求由Filter完成,
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping(value="testLogin",method = RequestMethod.GET)
	public String testLogin() {
		return "account/login";
	}

	
	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String login() {
		//如果已登录，跳转到首页，否则进入登录页面
		if(SecurityUtils.getSubject().isAuthenticated()){
			return "redirect:/";
		}else{
			return "account/login";
		}
		
	}

	@RequestMapping(value = "oauthFailure", method = RequestMethod.GET)
	public String fail(@RequestParam(WeixinOAuthAuthenticationFilter.ERROR_CODE_PARAM) String errcode,
			@RequestParam(WeixinOAuthAuthenticationFilter.ERROR_MSG_PARAM) String errmsg, Model model) {

		model.addAttribute(WeixinOAuthAuthenticationFilter.ERROR_CODE_PARAM, errcode);
		model.addAttribute(WeixinOAuthAuthenticationFilter.ERROR_MSG_PARAM, errmsg);
		return "account/oauthFailure";
	}
	
	/**
	 * 从浏览器端登录系统，仅仅供开发调试页面时使用
	 * https://open.weixin.qq.com/connect/oauth2/authorize&jsessionid=1jt427wzo17nsfxvcjrjn9qcy?appid=wxb02a7add18dd8b2b
	 * &redirect_uri=http://wx.wonderlink.com.cn/wxstore/weixinOAuthLogin&response_type=code&scope=snsapi_userinfo&state=567#wechat_redirect
	 * 
	 * http://wx.wonderlink.com.cn/wxstore/login/webLogin/oMBADjx7A-WOHIiVselNph0Gqqfo
	 * @param errcode
	 * @param errmsg
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "webLogin/{openid}", method = RequestMethod.GET)
	public String webLogin(@PathVariable("openid") String openid, Model model) {
		logger.info("webLogin ==========>{openid：" + openid + "}");
		Subject currentUser = SecurityUtils.getSubject();

		if (!currentUser.isAuthenticated()) {
			logger.info("logine---------未登录");
			// 登录系统
			logger.info("logine---------已绑定微信，根据openId登录系统：openId:" + openid);
			WeixinOAuthToken token = new WeixinOAuthToken(ShiroDbRealm.test_token, openid);
			currentUser.login(token);

		} else {
			logger.info("logine---------已登录");
		}
		return "redirect:/";
	}

}
